import React from 'react';
import { inject, observer } from 'mobx-react';
import { routerShape } from 'react-router';
import { WeaTableNew } from 'comsMobx';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaLocaleProvider,
} from 'ecCom';
import { Button, Modal } from 'antd';
import { toJS } from 'mobx';

const confirm = Modal.confirm;

import { listRoute, nameUpperCase } from '../util/index';

const store = ['routing', 'emailMainStore', 'emailAttachmentStore'].concat(
  listRoute.map(l => `email${nameUpperCase(l)}Store`),
);

import * as EmailUtil from '../util/EmailUtil';

const getLabel = WeaLocaleProvider.getLabel;
/**
 * 邮件 - 附件中心
 */
@inject(...store)
@observer
class Attachment extends React.Component {
  static defaultProps = {
    prefixCls: 'wea-email-attachment',
  };

  static contextTypes = {
    router: routerShape,
  };

  constructor(props) {
    super(props);

    this.tableHight = 200;
  }

  componentDidMount() {
    const { emailAttachmentStore } = this.props;
    emailAttachmentStore.doTableLoading(); // 初始化列表
    emailAttachmentStore.initConditionDatas(); // 初始化高级搜索区域
    this.getTableHeight();
  }

  componentWillReceiveProps(nextProps) {
    const { emailAttachmentStore } = this.props;
    const {
      location: { pathname, key },
    } = this.props;
    const {
      location: {
        pathname: _pathname,
        key: _key,
        query: { ontabchange },
      },
    } = nextProps;
    if (
      (pathname !== _pathname || key !== _key) &&
      !ontabchange &&
      _pathname.indexOf('main/email/attachment') > -1
    ) {
      emailAttachmentStore.setShowSearchAd(false);
      emailAttachmentStore.clearFormFields();
      emailAttachmentStore.clearSort(); // 初始化排序
      emailAttachmentStore.doTableLoading(); // 初始化列表
    }
  }

  componentDidUpdate() {
    this.getTableHeight();
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { emailAttachmentStore } = this.props;

    emailAttachmentStore.setShowSearchAd(false);
    emailAttachmentStore.clearFormFields();
    emailAttachmentStore.clearSort(); // 初始化排序
  }

  getTableHeight = () => {
    let content = document.getElementById('tablelist');
    let height = content && content.clientHeight;
    this.tableHight = height - 200;
  };

  setShowSearchAd = (bool) => {
    this.props.emailAttachmentStore.setShowSearchAd(bool);
  };
  hideSearchAd = () => this.props.emailAttachmentStore.setShowSearchAd(false);
  onSearch = () => {
    const {
      emailAttachmentStore: { searchParamsAd, doTableLoading },
    } = this.props;
    doTableLoading(searchParamsAd);
  };
  onSearchChange = (v) => {
    this.props.emailAttachmentStore.appendFormFields({ filename: v });
  };

  render() {
    const { emailAttachmentStore, prefixCls } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      conditioninfo,
      showSearchAd,
    } = emailAttachmentStore;
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@wbtuic@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@oucst8@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@dm8kbo@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    let values = this.getTableSelectedValues();
    return (
      <div className={prefixCls}>
        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@4ror20`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          {/* <div className={`${prefixCls}-main`}> */}
          <div className={`${prefixCls}-container`}>
            <div className={`${prefixCls}-title`}>
              {getLabel(21704, '附件列表')}
            </div>
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@tu73xs`}
              buttonsAd={buttonsAd}
              rightStyle={{ backgroundColor: '#f4f4f4' }}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().filename
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={EmailUtil.getSearchs(form, conditioninfo, () => {
                emailAttachmentStore.setShowSearchAd(false);
                emailAttachmentStore.doTableLoading();
              })}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />

            <div
              className={`${prefixCls}-container-content`}
              id="tablelist"
              ref="tablelist"
            >
              <WeaTable
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaTable@4yre71`}
                comsWeaTableStore={comsWeaTableStore}
                loading={loading}
                needScroll={true}
                hasOrder={true}
                getColumns={this.getNewColumns}
                scroll={{ y: this.tableHight }}
              />
            </div>
          </div>
          <div className={`${prefixCls}-bottom`}>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@ancb55`}
              type="primary"
              disabled={!values.length}
              onClick={this.createNewMail}
            >
              {getLabel(81300, '写 信')}
            </Button>
            <Button
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_Button@qvtm85`}
              type="primary"
              disabled={!values.length}
              onClick={() => this.downloadFile()}
            >
              {getLabel(32407, '批量下载')}
            </Button>
          </div>
          {/* </div> */}
        </WeaRightMenu>
      </div>
    );
  }

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { emailAttachmentStore } = this.props;
    if (key == 'search') {
      emailAttachmentStore.doTableLoading();
      emailAttachmentStore.setShowSearchAd(false);
    } else if (key == 'ShowCustomColumns') {
      const { comsWeaTableStore, sessionkey } = toJS(emailAttachmentStore);
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  onTabSearch = () => {
    const { emailAttachmentStore } = this.props;
    emailAttachmentStore.setShowSearchAd(false);
    emailAttachmentStore.doTableLoading();
  };

  onTabReset = () => {
    const { emailAttachmentStore } = this.props;
    emailAttachmentStore.clearFormFields();
  };
  onTabCancel = () => {
    const { emailAttachmentStore } = this.props;
    emailAttachmentStore.setShowSearchAd(false);
  };

  // 自定义过滤渲染
  getNewColumns = columns =>
    columns.map((column) => {
      let newColumn = { ...column };
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex == 'subject') {
          return (
            <div
              className="wea-url-name"
              style={{ cursor: 'pointer' }}
              title={text}
              onClick={() => {
                this.viewMail(record.mailid, record.subject);
              }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        } else if (newColumn.dataIndex == 'filename') {
          return (
            <div
              className="wea-url-name"
              style={{ cursor: 'pointer' }}
              title={text}
              onClick={() => {
                this.downloadFile(record.id);
              }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
            />
          );
        }
        return (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
          />
        );
      };
      return newColumn;
    });

  // 执行搜索方法（也可用于刷新table）
  executeSearch() {
    const { emailAttachmentStore } = this.props;
    emailAttachmentStore.setShowSearchAd(false);
    emailAttachmentStore.doTableLoading();
  }

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues() {
    const { emailAttachmentStore } = this.props;
    const { comsWeaTableStore } = emailAttachmentStore;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values.slice();
  }

  // 写信
  createNewMail = () => {
    let fileid = this.getTableSelectedValues();
    const {
      emailMainStore: { sysConfig },
      routing,
      emailAttachmentStore: { comsWeaTableStore },
    } = this.props;
    let attachSelectCount = comsWeaTableStore.selectedRowKeys.length;
    let attachCount = sysConfig.attachmentCount;
    if (attachCount < attachSelectCount) {
      confirm({
        content: `${`${
          getLabel(388819, '已选附件个数已超过邮件后台附件设置的附件总数') +
          attachCount
        },${getLabel(513069, '请重新选择或设置')}`}`,
      });
    } else if (fileid) {
      routing.push(
        `main/email/new?fileid=${fileid}&title=${getLabel(81300, '写信')}`,
      );
    }
  };

  // 批量下载
  downloadFile = (fileids) => {
    if (!fileids) {
      fileids = this.getTableSelectedValues();
    }
    if (fileids) {
      window.open(
        `/weaver/weaver.email.FileDownloadLocation?download=1&fileid=${fileids}`,
      );
    }
  };

  // 查看邮件
  viewMail = (id, subject) => {
    const {
      emailMainStore: { addViewStore },
      routing,
    } = this.props;
    addViewStore(id, 'inTab');
    routing.push(
      `main/email/view?id=${id}&title=${
        subject || getLabel(384186, '查看邮件')
      }`,
    );
  };
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@zyyg7i`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(Attachment);
